﻿@using KC.Web.Admin.Constants
@using KC.MVC.Core.Constants
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService
@{
    ViewData["Title"] = "存储池管理";
    Layout = "~/Views/Shared/_ListLayout.cshtml";
}

<div id="toolbar">
    <div>
        @*存储池管理-保存存储连接*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "F258F8A9-B2A1-4779-AA39-D0079541E5DA")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-plus" onclick="addStoragePool()">添加</a>
        }
        @*存储池管理-保存存储连接*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "F258F8A9-B2A1-4779-AA39-D0079541E5DA")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-pencil" onclick="editStoragePool()">编辑</a>
        }
        @*存储池管理-删除存储连接*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "C10FB77B-DEEC-4609-91C2-A8B8079A1135")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-trash" onclick="removeStoragePool()">删除</a>
        }
    </div>

    <div>
        <label>访问名称:</label>
        <input id="selectname" class="easyui-textbox" style="width: 200px" data-options="prompt:'请输入查询值'" />
        <a id="searchname"></a>
        <a href="javascript:void(0)" onclick="RefreshSearch()" class="easyui-linkbutton" data-options="iconCls:'fa fa-refresh'">刷新</a>
    </div>
</div>
<table id="datagrid" title=""></table>

@section scripts
    {
    <script type="text/javascript" src="@(KC.Framework.Base.GlobalConfig.ResWebDomain)lib/jquery-easyui/datagrid-detailview.js"></script>
    <script type="text/javascript">
        $(function () {
            InitDataGrid();
            $("#searchname").linkbutton({
                iconCls: "fa fa-search",
                text: "查询",
                onClick: function () {
                    searchData();
                }
            });
        });

        var loadDataUrl = '@Url.Action(ActionName.StoragePool.LoadStoragePoolList, ControllerName.StoragePool)';
        var loadTenantUserListByStoragePoolIdUrl = '@Url.Action(ActionName.StoragePool.LoadTenantUserListByStoragePool, ControllerName.StoragePool)';
        var tenantDetailUrl = '@Url.Action(ActionName.Tenant.TenantDetail, ControllerName.Tenant)';
        function InitDataGrid() {
            var $dataGrid = $('#datagrid').datagrid({
                view: detailview,
                url: loadDataUrl,
                method: 'get',
                idField: 'StoragePoolId',
                striped: true,
                fitColumns: true,
                rownumbers: true,
                singleSelect: true,
                pagination: true,
                nowrap: false,
                fit: true,
                pageSize: 10,
                pageList: [10, 20, 50, 100],
                showFooter: false,
                toolbar: "#toolbar",
                //toolbar: [{ text: document.getElementById('toolbar') }],
                columns: [[
                    { field: 'StoragePoolId', title: 'Id', width: 30, align: 'left' },
                    { field: 'CloudTypeString', title: '云服务', width: 50, align: 'left' },
                    { field: 'StorageTypeString',title:'类型',width:80,align:'left'},
                    { field: 'Endpoint', title: '访问地址', width: 200, align: 'left' },
                    { field: 'AccessName', title: '访问名称', width: 100, align: 'left' },
                    //{ field: 'CreatedBy', title: '创建人', width: 100, align: 'left' },
                    //{ field: 'CreatedDate', title: '创建时间', formatter: Common.DateFormatter, width: 100, align: 'left' },
                    { field: 'PasswordExpiredTime', title: '密码过期时间', formatter: Common.DateFormatter, width: 100, align: 'left' , sortable: true},
                    { field: 'TenantCount', title: '租户个数', width: 50, align: 'left', editor: { type: 'numberbox', options: { min: 20, precision: 0 } } }
                ]],
                onBeforeLoad: function (param) {
                    /*var bId = $("#txtBId").val();
                    var AllSearchKey = $("#txtAllSearchKey").val();
                    param.bId = bId;
                    param.AllSearchKey = AllSearchKey;*/
                },
                onLoadSuccess: function (data) {
                },
                onLoadError: function () {
                },
                detailFormatter: function (index, row) {
                    return '<div style="padding:2px"><table class="ddv"></table></div>';
                },
                onExpandRow: function (index, row) {
                    var ddv = $(this).datagrid('getRowDetail', index).find('table.ddv');
                    ddv.datagrid({
                        url: loadTenantUserListByStoragePoolIdUrl + '?StoragePoolId=' + row.StoragePoolId + "&CloudType=" + row.CloudType,
                        fitColumns: true,
                        singleSelect: true,
                        rownumbers: true,
                        loadMsg: '',
                        height: 'auto',
                        columns: [[
                            { field: 'TenantName', title: '租户代码', width: 100, align: 'left' },
                            { field: 'TenantDisplayName', title: '租户名', width: 80, align: 'left',
                                formatter: function (value, row, index) {
                                    return '<a href="javascript:void(0);" onclick="MainPage_PostMessage(\'openPage\', \'' + tenantDetailUrl + '\', \'id=' + row.TenantId + '\')" style="text-decoration: none; color: #0000ff">' + value + '</a>';
                                }
                            },
                            { field: 'CloudTypeString', title: '云服务', width: 60, align: 'left' },
                            { field: 'VersionString', title: '版本类型', width: 40, align: 'left' },
                            { field: 'TenantTypeString', title: '店铺类型', width: 50, align: 'left' },
                            { field: 'NickName', title: 'NickName', width: 50, align: 'center' }
                        ]],
                        onResize: function () {
                            $('#datagrid').datagrid('fixDetailRowHeight', index);
                        },
                  onLoadSuccess: function () {

                            setTimeout(function () {
                                $('#datagrid').datagrid('fixDetailRowHeight', index);
                            }, 0);
                        }


                    });
                }
            });

            //$('#txtSearchbox').searchbox({
            //    menu: '#divSearchMenu',
            //    prompt: '请输入查询值',
            //    searcher: searchData
            //});
            $("#toolbar").keydown(function () {
                if (event.keyCode == "13") {
                    searchData();
                }

            });
        }

        var getFormUrl = '@Url.Action(ActionName.StoragePool.GetStoragePoolForm, ControllerName.StoragePool)';
        var saveFormUrl = '@Url.Action(ActionName.StoragePool.SaveStoragePoolForm, ControllerName.StoragePool)';
        function openForm(id) {
            var dialog = $.easyui.showDialog({
                title: "保存数据",
                width: 400,
                height: 300,
                href: getFormUrl + "?id=" + id,
                modal: true,
                topMost: false,
                enableHeaderContextMenu: false,
                enableApplyButton: false,
                onSave: function (d) {
                    var validate = d.form("enableValidation").form("validate");
                    if (validate) {
                        $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                        $.ajax({
                            async: true,
                            type: "post",
                            dataType: "json",
                            url: saveFormUrl,
                            data: AddAntiForgeryToken(d.form("getData")),
                            success: function (data) {
                                if (data.success) {
                                    d.window('close');
                                    if (data.Result) {
                                        $('#datagrid').datagrid('reload');
                                        $.messager.showInfoCenter('系统提示', '保存数据成功。', 1000);
                                    } else {
                                        $.messager.showErrorCenter('错误消息', '保存数据失败。', 1000);
                                    }
                                } else {
                                    $.messager.showErrorCenter('错误消息', data.message, 1000);
                                }
                            },
                            complete: function () {
                                $.easyui.loaded();
                            }
                        });
                        return false;
                    } else {
                        return false;
                    }
                },
                onLoad: function () {
                    var f = $(this), ret = $.fn.dialog.defaults.onLoad();
                    f.form("disableValidation").form("enableValidation");
                    return ret;
                }
            });
        }
        function RefreshSearch() {
            $("#selectname").searchbox('setValue', '');
            searchData();
        }
        //function searchData(value, name) {
        //    $('#datagrid').datagrid('unselectAll');
        //    $('#datagrid').datagrid('load', { "searchKey": name, "searchValue": value });
        //}
        function searchData() {
            $("#datagrid").datagrid('load', { selectname: $("#selectname").searchbox("getValue") });
        }
        function addStoragePool() {
            openForm(0);
        }
        function editStoragePool() {
            var row = $('#datagrid').datagrid('getSelected');
            if (row) {
                openForm(row.StoragePoolId);
            } else {
                $.messager.showErrorCenter('系统提示', '请选择需要编辑的数据', 2000);
            }
        }

        var removeUrl = '@Url.Action(ActionName.StoragePool.RemoveStoragePool, ControllerName.StoragePool)';
        function removeStoragePool() {
            var row = $('#datagrid').datagrid('getSelected');
            if (row) {
                $.messager.confirm('确认', '是否确定删除该条记录?', function(r) {
                    if (r) {
                        $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                        $.post(removeUrl, { id: row.StoragePoolId }, function(data) {
                            $.easyui.loaded();
                            if (data.success) {
                                if (data.Result) {
                                    $('#datagrid').datagrid('reload');
                                    $.messager.showInfoCenter('系统提示', '删除数据成功。', 1000);
                                } else {
                                    $.messager.showErrorCenter('错误消息', '删除数据失败。', 1000);
                                }
                            } else {
                                $.data.showErrorCenter('错误消息', data.message, 1000);
                            }
                        }, 'json');
                    }
                });
            } else {
                $.messager.showErrorCenter('系统提示', '请选择需要删除的数据', 2000);
            }
        }

        var getPasswordHashUrl = '@Url.Action(ActionName.Tenant.GeneratePasswordHash, ControllerName.Tenant)';
        function generatePasswordHash() {
            //debugger;
            var password = $('#AccessKeyPassword').val();
            if (password == '') {
                $.messager.showErrorCenter('错误消息', "用户密码不能为空", 1000);
                return;
            }
            $.messager.confirm('确认', '是否根据秘钥:（' + password + '）进行加密，生成加密后的秘钥?', function (r) {
                if (r) {
                    $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                    $.post(getPasswordHashUrl, { password: password }, function (result) {
                        $.easyui.loaded();
                        if (result.success) {
                            $('#AccessKeyPasswordHash').val(result.message);
                        } else {
                            $.messager.showErrorCenter('错误消息', result.message, 1000);
                        }
                    }, 'json');
                }
            });
        }

        var testConnectionUrl = '@Url.Action(ActionName.StoragePool.TestStorageConnection, ControllerName.StoragePool)';
        function testConnection() {
            //debugger;
            var cloudType = $('#CloudType').val();
            if (cloudType == '') {
                $.messager.showErrorCenter('错误消息', "云类型不能为空", 1000);
                return;
            }
            var endpoint = $('#Endpoint').val();
            if (endpoint == '') {
                $.messager.showErrorCenter('错误消息', "服务器地址不能为空", 1000);
                return;
            }
            var accessName = $('#AccessName').val();
            if (accessName == '') {
                $.messager.showErrorCenter('错误消息', "服务器AccessName不能为空", 1000);
                return;
            }
            var accessKeyHash = $('#AccessKeyPasswordHash').val();
            if (accessKeyHash == '') {
                $.messager.showErrorCenter('错误消息', "服务器AccessKey不能为空", 1000);
                return;
            }
            $.easyui.loading({ msg: '正在保存数据，请稍等...' });
            $.post(testConnectionUrl,
                {
                    CloudType: cloudType,
                    Endpoint: endpoint,
                    AccessName: accessName,
                    AccessKeyPasswordHash: accessKeyHash,
                },
                function (data) {
                    $.easyui.loaded();
                    if (data.success) {
                        if (data.Result == '') {
                            $.messager.showInfoCenter('系统提示', '测试存储连接成功。', 1000);
                        } else {
                            $.messager.showErrorCenter('错误消息', data.Result, 3000);
                        }
                    } else {
                        $.messager.showErrorCenter('错误消息', data.message, 1000);
                    }
                }, 'json');
        }
    </script>
}

